<?php
namespace Cli\Controller;

use Admin\Model\AdModel;

class RebuildCacheController extends ClibaseController
{
    public function index()
    {
        echo "+-----------------------------------------------------------------------+\n";
        echo "+ all              重建所有的缓存\n";
        echo "+ sysConfig        系统配置sysConfig\n";
        echo "+ channelList      渠道id和名称channelList\n";
        echo "+ affiliateList    网盟简称列表affiliateList\n";
        echo "+-----------------------------------------------------------------------+\n";
    }
    
    /**
     * 重建所有缓存
     */
    public function all()
    {
        $time = date('Y-m-d H:i:s');
        $start = microtime(true);
        echo "+-----------------------------------------------------------------------+\n";
        echo "+ 重建缓存key\n";
        echo "+ ".$time."\n";
        echo "+-----------------------------------------------------------------------+\n";
        $this->sysConfig();
        $this->channelList();
        $this->affiliateList();
        echo $this->spendTime($start, "全部执行完成");
    }

    /**
     * 重建系统配置缓存
     */
    public function sysConfig()
    {
        $start = microtime(true);
        try{
            $res = D('SysConfig')->makeAll();
            if(false===$res)
                throw new \Exception('redis异常');
            echo "系统配置更新成功";
        }catch(\Exception $e){
            $key = D('SysConfig')->cachekey_name;
            $msg = "系统配置更新失败\tkey:{$key}\t原因:".$e->getMessage();
            \Think\Log::write($msg);
        }
        echo $this->spendTime($start);
    }

    /**
     * 重建渠道id和名称的缓存
     */
    public function channelList()
    {
        $start = microtime(true);
        try{
            $res = D('Admin/SysChannel')->createChannelList();
            if(false===$res)
                throw new \Exception('redis异常');
            echo "渠道id和名称的缓存更新成功";
        }catch(\Exception $e){
            $key = D('Admin/SysChannel')->getChannelListKey();
            $msg = "渠道id和名称的缓存更新失败\tkey:{$key}\t原因:".$e->getMessage();
            \Think\Log::write($msg);
        }
        echo $this->spendTime($start);
    }

    /**
     * 重建渠道id和名称的缓存
     */
    public function affiliateList()
    {
        $start = microtime(true);
        try{
            $res = D('Admin/Ad')->setAffiliateCache();
            if(false===$res)
                throw new \Exception('redis异常');
            echo "网盟简称列表的缓存更新成功";
        }catch(\Exception $e){
            $key = D('Admin/Ad')->affiliate_cache_key;
            $msg = "网盟简称列表的缓存更新失败\tkey:{$key}\t原因:".$e->getMessage();
            \Think\Log::write($msg);
        }
        echo $this->spendTime($start);
    }

    /**
     * 重建缓存花费的时间
     * @param $start
     * @param string $type
     * @return string
     */
    public function spendTime($start, $type="")
    {
        return PHP_EOL.$type.'花费时间(秒): '.sprintf("%.5f", (microtime(true)-$start)).PHP_EOL.PHP_EOL;
    }
   
}
